<template>
  <div class="departments">
    <el-card>
      <el-tabs>
        <el-tab-pane label="组织结构">
          <!-- 头部 -->
          <div class="content">
            <Tree :data="topItem" />
            <hr>
            <!-- 树形控件 -->
            <el-tree :data="branch">
              <template v-slot="{ data }">
                <Tree style="width: 100%" :data="data" @getBranch="getBranch" />
                <!-- <div class="item" style="width: 100%">
                  <i class="el-icon-user-solid" />
                  <div class="title">{{ data.name }}</div>
                  <div class="user">{{ data.people }}</div>
                  <el-dropdown>
                    <span>操作
                      <i class="el-icon-arrow-down el-icon--right" />
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item>添加子部门</el-dropdown-item>
                        <el-dropdown-item>查看部门</el-dropdown-item>
                        <el-dropdown-item>删除部门</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div> -->
              </template>
            </el-tree>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 使用弹框组件 -->
    <Add :init-data="initData" @getBranch="getBranch" />
  </div>
</template>

<script>
import { companyDepartment } from '@/api/departments.js'
// 导入组件
import Tree from './components/tree.vue'
// 导入弹框组件
import Add from './components/add.vue'
export default {
  components: {
    Tree,
    Add
  },
  data() {
    return {
      // 树形数据
      branch: [],
      initData: [],
      topItem: {
        name: '',
        manager: '负责人',
        id: '',
        // 添加一个标识,用于是否显示顶部下拉多余项
        treeShow: true
      }
    }
  },
  created() {
    this.getBranch()
  },
  methods: {
    // 获取组织架构数据
    async getBranch() {
      const res = await companyDepartment()
      // 保存数据topItem的名字
      this.topItem.name = res.data.companyName
      console.log(res)
      this.initData = res.data.depts
      this.branch = this.getTree(res.data.depts, '')
    },
    // 数据转换成树形数据
    getTree(arr, pid) {
      return arr.filter((item) => {
        if (item.pid === pid) {
          item.children = this.getTree(arr, item.id)
          return true
        }
      })
    }
  }
}
</script>

<style lang="scss">
.departments {
  padding: 20px;
  .content {
    width: 85%;
    margin: 20px auto 0;
    .el-tree-node__content {
      height: 36px;
    }
  }
}
</style>
